/*
 * File Name：CWUpdate.java
 * Copyright：Copyright 2008-2015 CiWong.Inc. All Rights Reserved.
 * Description： CWUpdate.java
 * Modify By：bin
 * Modify Date：2015年4月23日
 * Modify Type：Add
 */
package com.ciwong.mobilelib.utils;

import android.Manifest;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Build;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.RemoteViews;
import android.widget.TextView;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.libs.utils.volley.AsyncDownload;
import com.ciwong.libs.utils.volley.BaseRequest;
import com.ciwong.libs.utils.volley.HttpRequest;
import com.ciwong.mobilelib.R;
import com.ciwong.mobilelib.application.BaseApplication;
import com.ciwong.mobilelib.bean.ApkUpdateInfo;
import com.ciwong.mobilelib.ui.InstallActivity;
import com.ciwong.mobilelib.widget.CWDialog;
import com.ciwong.mobilelib.xml.UpdateXmlHandler;

import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 习网升级类
 *
 * @author bin
 * @version ciwong v.1.0 2015年4月23日
 * @since ciwong v.1.0
 */
public class CWUpdate {
    /**
     * 更新出错
     */
    public static final int UPDATE_FLAG_ERROR = -1;

    /**
     * 下载apk出错
     */
    public static final int UPDATE_FLAT_DOWNLAOD_APK_ERROR = -2;

    /**
     * 已经是最新版本
     */
    public static final int UPDATE_FLAG_ISLATEST = 1;

    /**
     * 后台更新
     */
    public static final int UPDATE_BACKGROUND = 2;

    /**
     * 取消
     */
    public static final int UPDATE_CANCEL = 3;

    /**
     * 完成
     */
    public static final int COMPLETE = 4;

    /**
     * 是否提示更新版本信息标识
     */
    public static final String APK_UPDATE_CONFIG = "APK_UPDATE_CONFIG";

    /**
     * 更新周期配置(当用户点击不在更新后,提示用户再次更新的周期)
     */
    private static final String APK_UPDATE_EXPIRE_CONFIG = "APK_UPDATE_EXPIRE_CONFIG";


    public static final String APK_UPDATE_SERVICE_VERSION_CODE = "APK_UPDATE_SERVICE_VERSION_CODE";

    /**
     * 更新周期(当用户点击不在更新后,提示用户再次更新的周期)天
     */
    private int update_expire_time = -100;

    private static final int REQUEST_TIME_OUT = 5000;

    private static Object async = new Object();

    private static boolean versionTooLow;// 版本是否过低

    private static boolean isAutoUpdate;// 自动更新

    private static boolean isUpgraded;// 是否请求更新完成

    private Activity mContext;

    private String url;

    private Callback mCallback;

    private Timer mTimer;

    private HttpRequest request;

    private CWDialog mDialog;

    private TimerTask task = new TimerTask() {

        @Override
        public void run() {
            if (request != null && !isUpgraded) {
                BaseRequestUtil.getInstance().cancelAll(CWUpdate.this);
                request = null;
                if (mCallback != null) {
                    mCallback.excuteSelfMethod();
                    mCallback.excuteSelfMethod(UPDATE_FLAG_ERROR);
                }
                synchronized (async) {
                    isUpgraded = true;
                }
                CWLog.d("debug", "update cancel");
            }
        }
    };

    /**
     * 构造函数
     *
     * @param mContext  上下文
     * @param url       更新地址
     * @param mCallback 回调函数
     */
    public CWUpdate(Activity mContext, String url, Callback mCallback) {
        this.mContext = mContext;
        this.url = url;
        this.mCallback = mCallback;
    }

    /**
     * 执行请求
     *
     * @param autoUpdate 是否是自动更新
     */
    public void excute(final boolean autoUpdate) {
        synchronized (async) {
            isUpgraded = false;
        }
//        if (mCallback != null) {
//            mCallback.excuteSelfMethod(UPDATE_FLAG_ISLATEST);
//            mCallback.excuteSelfMethod();
//        }
        isAutoUpdate = autoUpdate;
        final int h = 24;
        final int m = 60 * 60 * 1000;
        long time = CWSys.getSharedLong(APK_UPDATE_EXPIRE_CONFIG, -1);
        if (time > 0) {
            update_expire_time = (int) ((System.currentTimeMillis() - time) / (m * h));
        }
        request = new HttpRequest(url, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError arg0) {
                if (mCallback != null) {
                    mCallback.excuteSelfMethod(UPDATE_FLAG_ERROR);
                    mCallback.excuteSelfMethod();
                }
            }
        }, new HttpRequest.ResponseCallback() {

            @Override
            public void error(int errorCode, String msg) {
                synchronized (async) {
                    if (isUpgraded) {
                        return;
                    }
                    isUpgraded = true;
                }
                CWLog.e("debug", "update app error    errorType:" + errorCode);
                if (mCallback != null) {
                    mCallback.excuteSelfMethod(UPDATE_FLAG_ERROR);
                    mCallback.excuteSelfMethod();
                }
            }

            @Override
            public void success(BaseRequest.XmlHandler xmlHandler) {
                mCallback.complete();
                UpdateXmlHandler mXmlHandler = (UpdateXmlHandler) xmlHandler;
                final ApkUpdateInfo mInfo = mXmlHandler.getUpdateInfo();
                int sysVersionCode = BaseSystem.getSystemVersionCode(mContext);
                final boolean isForceUpgrade = mInfo.getMinVersionCode() > sysVersionCode;
                final int showTips = mInfo.getShowTips();
                final int frequency = mInfo.getFrequency();
                CWLog.d("CWUpdate", "isForceUpgrade:" + isForceUpgrade
                        + "     isUpgraded:" + isUpgraded);

                CWSys.setSharedInt(APK_UPDATE_SERVICE_VERSION_CODE, mInfo.getVersionCode());
                if (mInfo.getVersionCode() <= sysVersionCode) {
                    BaseApplication.getInstance().isVersionUpdate = true;
                }
                synchronized (async) {
                    if (isUpgraded && !isForceUpgrade) {
                        return;
                    }
                    isUpgraded = true;
                }
                if (isForceUpgrade) {
                    //强制升级
                    versionTooLow = true;
                    showUpdate(mInfo);
                } else if (mInfo.getVersionCode() > sysVersionCode) {
                    //提示升级
                    boolean isShowUpdate = false;
                    if (autoUpdate) {
                        if (showTips == 1) {
                            if (update_expire_time == -100 || update_expire_time >= frequency) {
                                isShowUpdate = true;
                            }
                        }
                    } else {
                        isShowUpdate = true;
                    }
                    if (isShowUpdate) {
                        CWSys.setSharedLong(APK_UPDATE_EXPIRE_CONFIG, System.currentTimeMillis());
                        showUpdate(mInfo);
                    } else {
                        BaseApplication.getInstance().isVersionUpdate = true;
                    }
                } else {
                    if (mCallback != null) {
                        mCallback.excuteSelfMethod(UPDATE_FLAG_ISLATEST);
                        mCallback.excuteSelfMethod();
                    }
                }
            }
        });
        if (isAutoUpdate) {
            request.setRetryPolicy(new DefaultRetryPolicy(REQUEST_TIME_OUT, 0,
                    DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        }
        request.setResponseDataType(HttpRequest.RESPONSE_DATA_TYPE_XML_HANDLER);
        request.setXmlHandler(new UpdateXmlHandler());
        BaseRequestUtil.getInstance().add(request, this);
    }

    private void showUpdate(final ApkUpdateInfo mInfo) {
        CWDialog updateDialog = new CWDialog(mContext, false, false);
        View root = LayoutInflater.from(mContext).inflate(
                R.layout.libs_apk_update_info, null);
        updateDialog.setTitleTextColor(Color.BLACK);
//        CheckBox noRemainMe = (CheckBox) root.findViewById(R.id.noRemainMe);
//        if (versionTooLow || !isAutoUpdate)
//        {
//            noRemainMe.setVisibility(View.INVISIBLE);
//        }

//        noRemainMe
//                .setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
//                {
//                    @Override
//                    public void onCheckedChanged(CompoundButton buttonView,
//                            boolean isChecked)
//                    {
//                        CWSys.setSharedBoolean(APK_UPDATE_CONFIG, isChecked);
//                        if (isChecked)
//                        {
//                            CWSys.setSharedLong(APK_UPDATE_EXPIRE_CONFIG,
//                                    System.currentTimeMillis());
//                        }
//                    }
//                });
        TextView updateInfos = (TextView) root.findViewById(R.id.updateInfos);
        String info = "";
        for (String s : mInfo.getUpdateInfos()) {
            info += s + "\n";
        }
        updateDialog.setTitle(mContext.getString(R.string.update_info,
                mInfo.getVersionName()));
        updateDialog.setIcon(R.mipmap.ic_update);
        updateInfos.setText(info);
        updateDialog.setContentView(root);
        updateDialog.setCancelable(false);
        updateDialog.setPositiveButton(R.string.update_immediately,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        showGetSDcardPermissDialog(mInfo);
                    }
                });
        if (!versionTooLow) {
            updateDialog.setNegativeButton(R.string.update_temporary,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (versionTooLow) {
                                exit();
                            } else if (mCallback != null) {
                                mCallback.excuteSelfMethod();
                                mCallback.excuteSelfMethod(UPDATE_CANCEL);
                            }
                        }
                    });
        }
        if (mContext instanceof Activity) {
            if (!((Activity) mContext).isFinishing()) {
                if (!updateDialog.isShowing()) {

                    updateDialog.show();
                }
            }
        } else {
            if (!updateDialog.isShowing()) {
                updateDialog.show();
            }
        }
    }

    private void exit() {
        boolean isExcute = false;
        if (mCallback != null) {
            isExcute = mCallback.exitApp();
        }
        if (mContext instanceof Activity && !isExcute) {
            Activity temp = (Activity) mContext;
            if (!temp.isFinishing()) {
                temp.finish();
            }
        }
    }

    /**
     * 更新应用
     *
     * @author PLA-ZJLIU
     */
    public static class UpdateVersion {
        /**
         * ID
         */
        public static final int ID = 0x56464dd;

        /**
         * 应用文件地址
         */
        public static final String APK_FILE_PATH = CWSys.getCiwongRoot()
                + "/download/";

        private static NotificationManager manager;

        private boolean backgroundUpdate;// 是否后台更新

        private final Context mContext;

        private final NotificationManager mNotificationManager;

        private final Notification mNotification;

        private final Resources mResources;

        private final String downloadUrl;

        private final int[] indicates = new int[]{
                R.mipmap.stat_sys_download_anim1,
                R.mipmap.stat_sys_download_anim2,
                R.mipmap.stat_sys_download_anim3,
                R.mipmap.stat_sys_download_anim4,
                R.mipmap.stat_sys_download_anim5};

        private final int len = indicates.length;

        private final String versionCode;

        private final String apkFileName;

        private Callback mCallback;

        private DecimalFormat format = new DecimalFormat("0.00");

        private int index = 0;

        /**
         * 构造函数
         *
         * @param mContext    {@link Activity}
         * @param versionCode 版本名称
         * @param apkFileName 应用的文件名称
         * @param downloadUrl 下载地址
         * @param callback    回调接口
         */
        public UpdateVersion(Context mContext, String versionCode,
                             String apkFileName, String downloadUrl, Callback callback) {
            this.mContext = mContext;
            this.versionCode = versionCode;
            this.apkFileName = apkFileName;
            this.downloadUrl = downloadUrl;
            this.mCallback = callback;
            File f = new File(APK_FILE_PATH);
            if (!f.exists()) {
                f.mkdirs();
            }
            mNotificationManager = (NotificationManager) mContext
                    .getSystemService(Context.NOTIFICATION_SERVICE);
            manager = mNotificationManager;
            mResources = mContext.getResources();
            final String apkName = mResources.getString(R.string.app_name);
            mNotification = new Notification(indicates[0],
                    mResources.getString(R.string.downing_update, apkName),
                    System.currentTimeMillis());
            RemoteViews views = new RemoteViews(mContext.getPackageName(),
                    R.layout.libs_download_notice_view);
            views.setTextViewText(R.id.app_version_info, apkName + "    "
                    + mResources.getString(R.string.version_code, versionCode));
            mNotification.contentView = views;
        }

        /**
         * 获取当前的通知对象
         *
         * @return {@link NotificationManager}
         */
        public static NotificationManager getNotificationManager() {
            return manager;
        }

        /**
         * 开始下载
         */
        public void startDownload() {
            final int count = 5;
            final AsyncDownload mDownload = AsyncDownload.getInstance();
            AsyncDownload.setMaxDownloadCount(count);
            final CWDialog mDownloadDialog = new CWDialog(mContext);
            View root = LayoutInflater.from(mContext).inflate(
                    R.layout.libs_update_download, null);
            final ProgressBar downloadProgress = (ProgressBar) root
                    .findViewById(R.id.downloadProgress);
            final TextView downloadPercent = (TextView) root
                    .findViewById(R.id.downloadPercent);
            final TextView downloadAppSize = (TextView) root
                    .findViewById(R.id.downloadAppSize);
            mDownloadDialog.setContentView(root);
            mDownloadDialog.setIcon(R.mipmap.ic_update);
            index++;
            mDownloadDialog.setTitle(R.string.downloading);
            mDownloadDialog.setCancelable(false);
            BaseApplication.getInstance().isVersionUpdate = false;
            if (!versionTooLow) {
                mDownloadDialog.setPositiveButton(android.R.string.cancel,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                mDownload.cancel(downloadUrl);
                                if (mCallback != null) {
                                    mCallback.excuteSelfMethod();
                                    mCallback.excuteSelfMethod(UPDATE_CANCEL);
                                }

                            }
                        });
                mDownloadDialog.setNegativeButton(R.string.update_background,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                backgroundUpdate = true;
                                if (mCallback != null) {
                                    mCallback.excuteSelfMethod();
                                    mCallback
                                            .excuteSelfMethod(UPDATE_BACKGROUND);
                                }
                            }
                        });
            }
            if (mContext instanceof Activity) {
                if (!((Activity) mContext).isFinishing()) {
                    mDownloadDialog.show();
                }
            } else {
                mDownloadDialog.show();
            }
            File f = new File(APK_FILE_PATH + apkFileName);
            f.delete();
            mDownload.addTask(downloadUrl, null, f.getAbsolutePath(),
                    new AsyncDownload.OnProgressUpdate() {
                        @Override
                        public void progressUpdate(long total, long progress,
                                                   Object tag) {
                            if (backgroundUpdate) {
                                send((int) progress, (int) total);
                            } else {
                                index++;
                                if (index >= len) {
                                    index = 0;
                                }
                                downloadProgress.setMax((int) total);
                                total = total == 0 ? 1 : total;
                                downloadProgress.setProgress((int) progress);
                                downloadPercent.setText(format
                                        .format(((float) progress * 100)
                                                / ((float) total))
                                        + "%");
                                downloadAppSize.setText(total / 1024 + "MB");
                            }
                        }

                        @Override
                        public void error(int errorType,
                                          AsyncDownload.DownloadTask task) {
                            addTaskError(errorType, task, mDownloadDialog);
                        }

                        @Override
                        public void completed(AsyncDownload.DownloadTask task) {
                            instanll(mDownloadDialog);
                            mCallback.excuteSelfMethod();
                            mCallback
                                    .excuteSelfMethod(COMPLETE);
                        }

                        @Override
                        public void complete(long total, Object tag)

                        {
                            instanll(mDownloadDialog);
                            mCallback.excuteSelfMethod();
                            mCallback
                                    .excuteSelfMethod(COMPLETE);
                        }
                    }, downloadUrl);
        }

        private void addTaskError(int errorType,
                                  AsyncDownload.DownloadTask task, CWDialog dialog) {
            CWLog.e("debug", "download update apk error    errorType:"
                    + errorType + "     download url:" + task.getDownloadUrl());
            if (mCallback != null) {
                mCallback.excuteSelfMethod();
                mCallback.excuteSelfMethod(UPDATE_FLAG_ERROR,
                        UPDATE_FLAT_DOWNLAOD_APK_ERROR);
            }
            if (!backgroundUpdate && !versionTooLow) {
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
            }
            if (backgroundUpdate) {
                send(-1, -1);
            }
            if (versionTooLow) {
                exit(true);
            }
        }

        private void exit(boolean isFinish) {
            boolean isExcute = false;
            if (mCallback != null) {
                isExcute = mCallback.exitApp();
            }
            if (mContext instanceof Activity && !isExcute) {
                Activity temp = (Activity) mContext;
                if (!temp.isFinishing() && isFinish) {
                    temp.finish();
                }
            }
        }

        void instanll(CWDialog mDownloadDialog) {
            if (!backgroundUpdate) {
                if (mContext instanceof Activity) {
                    if (!((Activity) mContext).isFinishing()) {
                        mDownloadDialog.dismiss();
                    }
                } else {
                    mDownloadDialog.dismiss();
                }
                install();
                if (!versionTooLow) {
                    mCallback.excuteSelfMethod();
                } else {
                    exit(true);
                }
            } else {
//                Intent mIntent = new Intent(mContext, InstallActivity.class);
//                mIntent.putExtra(UpdateVersion.APK_FILE_PATH,
//                        UpdateVersion.APK_FILE_PATH + apkFileName);
//                mNotification.flags = Notification.DEFAULT_SOUND;
//                mNotification.icon = R.mipmap.ic_update;
//                PendingIntent mPendingIntent = PendingIntent
//                        .getActivity(mContext, 0, mIntent,
//                                PendingIntent.FLAG_UPDATE_CURRENT);
//                mNotification.setLatestEventInfo(mContext,
//                        mContext.getString(R.string.app_name),
//                        mContext.getString(R.string.update_download_complete),
//                        mPendingIntent);
//                mNotificationManager.notify(ID, mNotification);


//                Intent mIntent = new Intent(mContext, InstallActivity.class);
//
//
//                mIntent.putExtra(UpdateVersion.APK_FILE_PATH,
//                        UpdateVersion.APK_FILE_PATH + apkFileName);
//
//                mNotification.flags = Notification.DEFAULT_SOUND;
////                mNotification.icon = R.mipmap.ic_update;
//
//                PendingIntent mPendingIntent = PendingIntent.getActivity(mContext, 0, mIntent,
//                        PendingIntent.FLAG_UPDATE_CURRENT);
//
////                mNotification.setLatestEventInfo(mContext,
////                        mContext.getString(R.string.app_name),
////                        mContext.getString(R.string.update_download_complete),
////                        mPendingIntent);
//
//                Notification.Builder builder = new Notification.Builder(mContext);
//                builder.setSmallIcon(R.mipmap.ic_update);
//
//                builder.setContentTitle(mContext.getString(R.string.app_name));
//                builder.setContentText(mContext.getString(R.string.update_download_complete));
//                builder.setContentIntent(mPendingIntent);
//                Notification notification = builder.build();
//
//                mNotificationManager.notify(ID, notification);

                install();
            }
        }

        void send(int currentSize, int totoalSize) {
            final int v = 13;
            final RemoteViews views = mNotification.contentView;
            if (totoalSize == -1 && currentSize == -1) {
                mNotificationManager.cancel(ID);
                views.setViewVisibility(R.id.download_progress, View.GONE);
                views.setViewVisibility(R.id.download_app_size, View.GONE);
                views.setTextViewText(R.id.download_percent, "下载失败");
                mNotification.flags = Notification.FLAG_AUTO_CANCEL;
                if (Integer.parseInt(Build.VERSION.SDK) <= v) {
                    PendingIntent mPendingIntent = PendingIntent.getActivity(
                            mContext, 0, new Intent(mContext,
                                    InstallActivity.class),
                            PendingIntent.FLAG_UPDATE_CURRENT);
                    mNotification.contentIntent = mPendingIntent;
                }
            } else {
                currentSize = currentSize > totoalSize ? totoalSize
                        : currentSize;

                views.setImageViewResource(R.id.download_indicate,
                        indicates[index]);
                views.setTextViewText(
                        R.id.download_percent,
                        format.format(((float) currentSize * 100)
                                / ((float) totoalSize))
                                + "%");
                views.setProgressBar(R.id.download_progress, totoalSize,
                        currentSize, false);
                mNotification.icon = indicates[index];
                mNotification.tickerText = mContext
                        .getString(R.string.app_name);
                views.setTextViewText(R.id.download_app_size, totoalSize / 1024 + "MB");
                mNotification.flags = Notification.FLAG_ONGOING_EVENT
                        | Notification.DEFAULT_SOUND;
                if (Integer.parseInt(Build.VERSION.SDK) <= v) {
                    PendingIntent mPendingIntent = PendingIntent.getActivity(
                            mContext, 0, new Intent(mContext,
                                    InstallActivity.class),
                            PendingIntent.FLAG_UPDATE_CURRENT);
                    mNotification.contentIntent = mPendingIntent;
                }
                // if (currentSize == totoalSize)
                // {
                // Intent mIntent = new Intent(mContext, InstallActivity.class);
                // mNotification.contentIntent = PendingIntent
                // .getActivity(mContext, 0, mIntent,
                // PendingIntent.FLAG_UPDATE_CURRENT);
                // }
                index++;
                if (index >= len) {
                    index = 0;
                }
            }

            mNotificationManager.notify(ID, mNotification);
        }

        private void install() {
            BaseJumpManager
                    .jumpToInstall(mContext, APK_FILE_PATH + apkFileName);

            // 2013-06-06 modify by jejun
            // mNotificationManager.cancel(ID);
            // Uri uri = Uri.parse("file://" + APK_FILE_PATH + apkFileName);
            // CWLog.i("debug", APK_FILE_PATH + apkFileName);
            // Intent intent = new Intent(Intent.ACTION_VIEW);
            // intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            // intent.setDataAndType(uri,
            // "application/vnd.android.package-archive");
            // mContext.startActivity(intent);
        }
    }

    /**
     * 回调接口
     *
     * @author res-qqlin
     */
    public abstract static class Callback {
        /**
         * 执行自己的方法
         */
        public void excuteSelfMethod() {

        }

        /**
         * 执行自己的方法(用于手动检查)
         *
         * @param obj obj[0]=检查更新是否成功,{@link #UPDATE_FLAG_ERROR},
         *            {@link #UPDATE_FLAG_ISLATEST}
         */
        public void excuteSelfMethod(Object... obj) {

        }

        /**
         * 退出整个应用
         *
         * @return 调用 者是否处理了退出应用
         */
        public boolean exitApp() {
            return false;
        }

        /**
         * 完成(升级网络请求完成)
         */
        public void complete() {

        }

    }

    private void updateDialog(final ApkUpdateInfo info, final Callback callback) {
        mDialog = new CWDialog(mContext, false, false);
        mDialog.setTitle(R.string.version_too_low_alert);
        mDialog.setCancelable(false);
        mDialog.setTitleTextColor(Color.BLACK);
        mDialog.setMessage(R.string.version_too_low_info)
                .setPositiveButton(android.R.string.ok,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                showUpdate(info);
                            }
                        })
                .setNegativeButton(android.R.string.cancel,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                boolean isExcute = false;
                                if (callback != null) {
                                    isExcute = callback.exitApp();
                                }
                                if (mContext instanceof Activity && !isExcute) {
                                    Activity temp = (Activity) mContext;
                                    if (!temp.isFinishing()) {
                                        temp.finish();
                                    }
                                }
                                if (callback != null) {
                                    callback.excuteSelfMethod(UPDATE_BACKGROUND);
                                    callback.excuteSelfMethod();
                                }
                            }
                        });
        if (mContext instanceof Activity) {
            if (!((Activity) mContext).isFinishing()) {
                mDialog.show();
            }
        } else {
            mDialog.show();
        }
    }

    private void startUpdate(final ApkUpdateInfo mInfo) {
        UpdateVersion mUpdate = new UpdateVersion(mContext,
                mInfo.getVersionName(), mInfo.getFileName(),
                mInfo.getDownloadUrl(), mCallback);
        mUpdate.startDownload();
    }

    public static final int CODE_REQUEST_WRITESD_PERMISSION = 8800;
    private CWDialog getSDcardPermissDialog;

    /**
     * 获取SDcard权限提示框
     */
    private boolean showGetSDcardPermissDialog(final ApkUpdateInfo mInfo) {
        boolean isHavePermiss = XXPermissionTool.isHasPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (isHavePermiss) {
            checkSDcardpermiss(mInfo);
        } else {
            if (getSDcardPermissDialog == null) {
                getSDcardPermissDialog = new CWDialog(mContext);
                getSDcardPermissDialog.setTitle(R.string.get_permiss_title);
                getSDcardPermissDialog.setTitleTextColor(Color.BLACK);
                getSDcardPermissDialog.setMessage(mContext.getString(R.string.get_sdcard_permiss_content), 16, Color.BLACK, Gravity.LEFT);
                getSDcardPermissDialog.setPositiveButton(R.string.get_permiss_ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getSDcardPermissDialog.dismiss();
                        checkSDcardpermiss(mInfo);
                    }
                });
                getSDcardPermissDialog.setNegativeButton(R.string.get_permiss_no, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getSDcardPermissDialog.dismiss();
                    }
                });
            }
            getSDcardPermissDialog.show();
        }
        return true;
    }

    /**
     * 使用sd卡，判断权限
     */
    private void checkSDcardpermiss(final ApkUpdateInfo mInfo) {
        if (Build.VERSION.SDK_INT >= 23
                && mContext.getApplicationInfo().targetSdkVersion >= 23) {
            BaseApplication.getInstance().isVersionUpdate = true;
            List<String> permissionList = new ArrayList<String>();
            Map<String, String> noteMap = new HashMap<>();
            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            noteMap.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, "本地存储权限");
            XXPermissionTool.checkPermissions(mContext, //
                    permissionList, //
                    noteMap, //
                    CODE_REQUEST_WRITESD_PERMISSION, //
                    new XXPermissionTool.OnCheckPermissionsFinishedListener() {
                        @Override
                        public void onCheckPermissionsFinished(int flag) {
                            if (0 == flag) {
                                startUpdate(mInfo);
                            } else {
                                showUpdate(mInfo);
                                BaseApplication.getInstance().isVersionUpdate = false;
                            }
                        }
                    });
        } else {
            startUpdate(mInfo);
        }
    }
}
